﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.Controllers;

namespace SSRS.Application.Web.Aop
{

    /// <summary>
    /// Discovers controllers from a list of <see cref="T:Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPart" /> instances.
    /// </summary>
    public class SsrsControllerFeatrueProvider : IApplicationFeatureProvider<ControllerFeature>, IApplicationFeatureProvider
    {
        private const string ControllerTypeNameSuffix = "BaseController";

        /// <inheritdoc />
        public void PopulateFeature(IEnumerable<ApplicationPart> parts, ControllerFeature feature)
        {
            foreach (IApplicationPartTypeProvider partTypeProvider in parts.OfType<IApplicationPartTypeProvider>())
            {
                foreach (TypeInfo type in partTypeProvider.Types)
                {
                    if (this.IsController(type) && !feature.Controllers.Contains(type))
                        feature.Controllers.Add(type);
                }
            }
        }

        /// <summary>
        /// Determines if a given <paramref name="typeInfo" /> is a controller.
        /// </summary>
        /// <param name="typeInfo">The <see cref="T:System.Reflection.TypeInfo" /> candidate.</param>
        /// <returns><code>true</code> if the type is a controller; otherwise <code>false</code>.</returns>
        protected virtual bool IsController(TypeInfo typeInfo)
        {
            return typeInfo.IsClass && !typeInfo.IsAbstract && (typeInfo.IsPublic && !typeInfo.ContainsGenericParameters) && (!typeInfo.IsDefined(typeof(NonControllerAttribute)) && (typeInfo.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase) || typeInfo.IsDefined(typeof(ControllerAttribute))));
        }
    }
}
